//
//  HJUserAccount.swift
//  HJWeiBo
//
//  Created by 黄珏 on 15/10/29.
//  Copyright © 2015年 黄珏. All rights reserved.
//

import UIKit

class HJUserAccount: NSObject,NSCoding {
    /// 接口获取授权后的access token
    var access_token: String?
    /// 当前授权用户的UID
    var uid: String?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            print("expires_date:\(expires_date)")
        }
    }
    /// 过期时间
    var expires_date: NSDate?
    /// 友好显示名称
    var name: String?

    init(dict:[String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
//    返回是否登入
    class var isUerLogin: Bool {
        return HJUserAccount.loadUserAccount() != nil
    }
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist"
    
    func saveAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: HJUserAccount.accountPath)
    }
   
    private static var userAccount: HJUserAccount?
     // 加载loadAccount 是用频繁,解档账号比较耗性能,只加载一次,保存到内存中,以后访问内存的中账号
    class func loadUserAccount() ->HJUserAccount? {
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? HJUserAccount
        }
//        判断是否过期
        if userAccount != nil && userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return userAccount
        }
        return nil
    }
    var avatar_large: String?
    // MARK: - 加载用户信息
    // 控制调用这个方法,不管成功还是失败,都需要告诉调用者
    func loadUserInfo(finish: (error: NSError?) -> ()) {
        NetworkTools.shareInstance.loadUserInfo { (result, error) -> () in
            if error != nil || result == nil {
//                自己的闭包自己决定什么时候调用
                finish(error: error)
                return
            }
            
            // 加载成功
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            // 保存到沙盒
            self.saveAccount()
            
            // 同步到内存中,把当前对象（因为是对象方法）赋值给内存中的 userAccount
            HJUserAccount.userAccount = self
            finish(error: nil)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
}
